import { defineStore } from "pinia";
import { store } from "@/store";
import type { userType, userLoginInfoType, userInfoType } from "./types";
import { setStore, getStore, removeStore } from "@/utils/store";

export const useUserStore = defineStore({
  id: "user",
  state: (): userType => ({
    // token
    token: getStore({ name: "token" }) || "",
    userInfo: getStore({ name: "userInfo" }) || {},
    rememberPwd: getStore({ name: "rememberPwd" }) || false,
    userLoginInfo: getStore({ name: "userLoginInfo" }) || {},
    roles: getStore({ name: "roles" }) || []
  }),
  actions: {
    /** 存储 token */
    SET_TOKEN(token: string) {
      this.token = token;
      setStore({ name: "token", content: this.token });
    },
    // 存储角色
    SET_ROLES(roles: string[]) {
      this.roles = roles;
      setStore({ name: "roles", content: this.roles });
    },
    /** 存储记住密码 */
    SET_REMEMBER_PWD(rememberPwd: boolean) {
      this.rememberPwd = rememberPwd;
      setStore({ name: "rememberPwd", content: this.rememberPwd });
    },
    /** 存储用户登录信息 */
    SET_USER_LOGIN_INFO(userLoginInfo: userLoginInfoType) {
      this.userLoginInfo = Object.assign(this.userLoginInfo, userLoginInfo);
      setStore({ name: "userLoginInfo", content: this.userLoginInfo });
    },
    SET_USER_INFO(userInfo: userInfoType) {
      this.userInfo = Object.assign(this.userInfo, userInfo);
      setStore({ name: "userInfo", content: this.userInfo });
    },
    LOGOUT() {
      this.token = "";
      this.userInfo = {};
      removeStore({ name: "token" });
      removeStore({ name: "userInfo" });
    }
  },
  getters: {
    getToken(): string | undefined {
      return this.token;
    },
    getUserInfo(): userInfoType | undefined {
      return this.userInfo;
    },
    getRoles(): string[] | undefined {
      return this.roles;
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
